package com.xzuf.extend;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;

import org.apache.commons.lang.StringUtils;

import com.xzuf.core.vo.xml.DataSourceVO;
import com.xzuf.core.vo.xml.SystemPropertyVO;
import com.xzuf.plugin.IModulePlugin;
import com.xzuf.pub.DbUtils;
import com.xzuf.pub.FileUtils;
import com.xzuf.pub.GlobalValue;
import com.xzuf.pub.GuiUtils;

/**
 * @author xzgf
 * @since 2008-7-16
 * @version 1.0
 */
public class DBSetUpPlugin implements IModulePlugin,ItemListener,ActionListener{
	
	private JLabel lb_dbList = null;
	
	private JComboBox cb_dbCommBox = null;
	
	private JLabel lb_dbType = null;
	
	private JComboBox cb_dbTypeCommBox = null;
	
	private JLabel lb_dbName = null;
	
	private JTextField tf_dbName = null;
	
	private JLabel lb_dbDriver = null;
	
	private JTextField tf_dbDriver = null;
	
	private JLabel lb_dbUrl = null;
	
	private JTextField tf_Url = null;
	
	private JLabel lb_dbUser = null;
	
	private JTextField tf_dbUser = null;
	
	private JLabel lb_dbPassword = null;
	
	private JPasswordField pf_dbPassword = null;
	
	private JCheckBox cbox_isDefault = null;
	
	private JButton btn_add = null;
	
	private JButton btn_modify = null;
	
	private JButton btn_save = null;
	
	private JButton btn_delete = null;
	
	private JButton btn_test = null;
	
	private JButton btn_cancel = null;
	
	private JPanel mainPanel = null;
	
	private int currentOpState = GlobalValue.OS_FREE;
	
	
	private void init() {
		
		lb_dbList = new JLabel("数据库列表");
		cb_dbCommBox = new JComboBox();
		cb_dbCommBox.addItemListener(this);
		lb_dbType = new JLabel("数据库类型");
		
		cb_dbTypeCommBox = new JComboBox();
		cb_dbTypeCommBox.setEnabled(false);
		cb_dbTypeCommBox.addItemListener(this);
		lb_dbDriver = new JLabel("驱动");
		tf_dbDriver = new JTextField(88);
		
		lb_dbUrl = new JLabel("Url");
		tf_Url = new JTextField(88);
		lb_dbUser = new JLabel("用户名");
		tf_dbUser = new JTextField(88);
		lb_dbPassword = new JLabel("密码");
		pf_dbPassword = new JPasswordField(88);
		lb_dbName = new JLabel("数据库名");
		tf_dbName = new JTextField(30);
		cbox_isDefault = new JCheckBox("默认");
		
		btn_add = new JButton("新增");
		btn_add.addActionListener(this);
		btn_modify = new JButton("修改");
		btn_modify.addActionListener(this);
		btn_save = new JButton("保存");
		btn_save.addActionListener(this);
		btn_delete = new JButton("删除");
		btn_delete.addActionListener(this);
		btn_test = new JButton("测试");
		btn_test.addActionListener(this);
		btn_cancel = new JButton("取消");
		btn_cancel.addActionListener(this);
		mainPanel = new JPanel();
		MigLayout layout = new MigLayout();
		mainPanel.setLayout(layout);
		
		mainPanel.add(lb_dbList,"cell 0 0");
		mainPanel.add(cb_dbCommBox,"cell 1 0");
		mainPanel.add(lb_dbType,"cell 0 1");
		mainPanel.add(cb_dbTypeCommBox,"cell 1 1");
		mainPanel.add(lb_dbName,"cell 2 1");
		mainPanel.add(tf_dbName,"cell 2 1");
		mainPanel.add(cbox_isDefault,"cell 2 1");
		mainPanel.add(lb_dbDriver,"cell 0 2");
		mainPanel.add(tf_dbDriver,"cell 1 2 2 1");
		mainPanel.add(lb_dbUrl,"cell 0 3");
		mainPanel.add(tf_Url,"cell 1 3 2 1");
		mainPanel.add(lb_dbUser,"cell 0 4");
		mainPanel.add(tf_dbUser,"cell 1 4 2 1");
		mainPanel.add(lb_dbPassword,"cell 0 5");
		mainPanel.add(pf_dbPassword,"cell 1 5 2 1");
		mainPanel.add(btn_add,"cell 0 6");
		mainPanel.add(btn_modify,"cell 1 6");
		mainPanel.add(btn_save,"cell 1 6");
		mainPanel.add(btn_delete,"cell 2 6");
		mainPanel.add(btn_test,"cell 2 6");
		mainPanel.add(btn_cancel,"cell 2 6");
		
		refreshDbTypeCommBox();
		refreshDbSourceCommBox();
		
		setComponentState(false);
	}
	
	private void setComponentState(boolean flag) {
		tf_dbDriver.setEditable(flag);
		tf_Url.setEditable(flag);
		tf_dbName.setEditable(flag);
		tf_dbUser.setEditable(flag);
		pf_dbPassword.setEditable(flag);
		cbox_isDefault.setEnabled(flag);
	}
	
	private void refreshDbTypeCommBox() {
		DefaultComboBoxModel model = new DefaultComboBoxModel();
		if(GlobalValue.sysProp != null) {
			List<DbPropertyVO> list = GlobalValue.sysProp.getDatabaseType().getContent();
			Iterator<DbPropertyVO> iter = list.iterator();
			while(iter.hasNext()) {
				DbPropertyVO vo = iter.next();
				model.addElement(vo);
				GlobalValue.dbPropertyMap.put(vo.getDbname(), vo);
			}
			cb_dbTypeCommBox.setModel(model);
			refreshDBPropItem((DbPropertyVO)cb_dbTypeCommBox.getSelectedItem());
		}
	}
	
	private void refreshDbSourceCommBox() {
		DefaultComboBoxModel model = new DefaultComboBoxModel();
		if(GlobalValue.sysProp != null) {
			List<DataSourceVO> list = GlobalValue.sysProp.getContent();
			Iterator<DataSourceVO> iter = list.iterator();
			while(iter.hasNext()) {
				DataSourceVO vo = iter.next();
				model.addElement(vo);
			}
			cb_dbCommBox.setModel(model);
		}
		refreshDSourceItem((DataSourceVO)cb_dbCommBox.getSelectedItem());
	}
	
	private void refreshDSourceItem(DataSourceVO vo) {
		tf_dbDriver.setText(vo.getDriverClassName());
		tf_dbUser.setText(vo.getUser());
		tf_Url.setText(vo.getDatabaseUrl());
		pf_dbPassword.setText(vo.getPassword());
		tf_dbName.setText(vo.getDataSourceName());
		cbox_isDefault.setSelected(vo.isDefault());
	}
	
	private void refreshDBPropItem(DbPropertyVO vo) {
		tf_dbDriver.setText(vo.getDriverClass());
		tf_dbUser.setText(vo.getUser());
		tf_Url.setText(vo.getUrl());
		pf_dbPassword.setText(vo.getPassword());
	}
	
	private void clearDBPropItem() {
		tf_dbDriver.setText("");
		tf_dbUser.setText("");
		tf_Url.setText("");
		pf_dbPassword.setText("");
		tf_dbName.setText("");
	}

	@Override
	public JPanel start() {
		init();
		return mainPanel;
	}
	
	private void onSave() {
		
		SystemPropertyVO vo = GlobalValue.sysProp;
		DataSourceVO dbSource = new DataSourceVO();
		
		if(tf_dbName.getText() == null || StringUtils.isEmpty(tf_dbName.getText())) {
			GuiUtils.showMessage("数据库名为空...", GlobalValue.mainFrame);
			return;
		}
		dbSource.setUser(tf_dbUser.getText());
		dbSource.setPassword(String.valueOf(pf_dbPassword.getPassword()));
		dbSource.setDriverClassName(tf_dbDriver.getText());
		dbSource.setDatabaseUrl(tf_Url.getText());
		dbSource.setDataSourceName(tf_dbName.getText());
		dbSource.setDatabaseType(((DbPropertyVO)cb_dbTypeCommBox.getSelectedItem()).getDbname());
		dbSource.setDefault(cbox_isDefault.isSelected());
		
		if(getCurrentOpState() == GlobalValue.OS_ADD) {
			vo.getContent().add(dbSource);
		} else if(getCurrentOpState() == GlobalValue.OS_EDIT) {
			List<DataSourceVO> list = vo.getContent();
			if(list != null && list.size() > 0) {
				ListIterator<DataSourceVO> iter = list.listIterator();
				while(iter.hasNext()) {
					DataSourceVO vpo = iter.next();
					if(vpo.getDataSourceName().equals(String.valueOf(cb_dbCommBox.getSelectedItem()))) {
						vpo.setUser(tf_dbUser.getText());
						vpo.setPassword(String.valueOf(pf_dbPassword.getPassword()));
						vpo.setDriverClassName(tf_dbDriver.getText());
						vpo.setDatabaseUrl(tf_Url.getText());
						vpo.setDataSourceName(tf_dbName.getText());
						vpo.setDatabaseType(((DbPropertyVO)cb_dbTypeCommBox.getSelectedItem()).getDbname());
						vpo.setDefault(cbox_isDefault.isSelected());
						iter.set(vpo);
						break;
					}
				}
			} else {
				vo.getContent().add(dbSource);
			}
			
		}
		
		try {
			FileUtils.saveSystemPropertyToXML(vo);
			setComponentState(false);
			GuiUtils.showMessage("保存成功...", GlobalValue.mainFrame);
			refreshDbSourceCommBox();
		} catch (FileNotFoundException e) {
			GuiUtils.showMessage("保存失败:" + e.getMessage(),GlobalValue.mainFrame);
		} catch (IOException e) {
			GuiUtils.showMessage("保存失败:" + e.getMessage(),GlobalValue.mainFrame);
		}
	}
	
	private void onAdd() {
		clearDBPropItem();
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		if(e.getSource() == cb_dbCommBox) {
			refreshDSourceItem((DataSourceVO)e.getItem());
		}
		if(e.getSource() == cb_dbTypeCommBox) {
			refreshDBPropItem((DbPropertyVO)e.getItem());
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btn_test) {
			DataSourceVO vo = new DataSourceVO();
			vo.setDriverClassName(tf_dbDriver.getText().trim());
			vo.setDatabaseUrl(tf_Url.getText().trim());
			vo.setUser(tf_dbUser.getText().trim());
			vo.setPassword(String.valueOf(pf_dbPassword.getPassword()));
			try {
				boolean flag = DbUtils.testDbCollection(vo);
				if(flag) 
					GuiUtils.showMessage("连接成功..", GlobalValue.mainFrame);
				else
					GuiUtils.showMessage("连接失败..", GlobalValue.mainFrame);
			} catch (Exception e1) {
				GuiUtils.showMessage("连接异常:" + e1.getMessage(), GlobalValue.mainFrame);
				e1.printStackTrace();
			}
		}
		
		if(e.getSource() == btn_save) {
			onSave();
			btn_add.setEnabled(true);
			btn_delete.setEnabled(true);
			btn_modify.setEnabled(true);
			btn_save.setEnabled(false);
			btn_test.setEnabled(true);
			btn_cancel.setEnabled(true);
		}
		if(e.getSource() == btn_modify) {
			setComponentState(true);
			setCurrentOpState(GlobalValue.OS_EDIT);
			btn_cancel.setEnabled(true);
			btn_delete.setEnabled(false);
			btn_add.setEnabled(false);
			btn_save.setEnabled(true);
			btn_modify.setEnabled(false);
			btn_test.setEnabled(false);
			refreshDSourceItem((DataSourceVO)cb_dbCommBox.getSelectedItem());
		}
		if(e.getSource() == btn_add) {
			setComponentState(true);
			setCurrentOpState(GlobalValue.OS_ADD);
			btn_test.setEnabled(false);
			btn_delete.setEnabled(false);
			btn_modify.setEnabled(false);
			btn_save.setEnabled(true);
			btn_add.setEnabled(false);
			btn_cancel.setEnabled(true);
			btn_test.setEnabled(true);
			cb_dbTypeCommBox.setEnabled(true);
			onAdd();
		}
		if(e.getSource() == btn_cancel) {
			setComponentState(false);
			btn_add.setEnabled(true);
			btn_modify.setEnabled(true);
			btn_delete.setEnabled(true);
			btn_cancel.setEnabled(false);
			btn_test.setEnabled(true);
			refreshDSourceItem((DataSourceVO)cb_dbCommBox.getSelectedItem());
		}
	}


	@Override
	public int getCurrentOpState() {
		return currentOpState;
	}

	@Override
	public void setCurrentOpState(int state) {
		currentOpState = state;
	}

}
